package Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.JDBC.DBConn;
import DAL.JDBC.UserJDBC;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public Register() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject registerResult = new JSONObject();
		UserJDBC userJDBC = new UserJDBC(DBConn.getConnection());
		
		
		String firstName = request.getParameter("fname");
		String lastName = request.getParameter("lname");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		String password = request.getParameter("password");
		
		try {
			if(
					firstName.length() == 0 	||
					lastName.length() == 0 		||
					email.length() == 0 		||
					phone.length() == 0 		||
					address.length() == 0 		||
					password.length() == 0)
			{
				registerResult.put("registerStatus", false);
				registerResult.put("message", "Must Fill All The Fields");
			}
				
			else if(isValidEmailAddress(email) == false)
			{
				registerResult.put("registerStatus", false);
				registerResult.put("message", "Email Is Not Valid");
			}
			else if(userJDBC.getUserByEmail(email) != null)
			{
				registerResult.put("registerStatus", false);
				registerResult.put("message", "Email Already Exists");
			}
				
			else
			{
				userJDBC.insert(firstName, lastName, email, phone, address, password);
				registerResult.put("registerStatus", true);
				registerResult.put("message", "Registration Succeeded!");
			}
		} 
		
		catch (JSONException e) {
			e.printStackTrace();
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(registerResult.toString());
		
	}
	
	public static boolean isValidEmailAddress(String email) {
		   boolean result = true;
		   try {
		      InternetAddress emailAddr = new InternetAddress(email);
		      emailAddr.validate();
		   } catch (AddressException ex) {
		      result = false;
		   }
		   return result;
		}

}
